using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using WpfClient.Core.Interfaces;
using WpfClient.Core.Models;
using WpfClient.Shared.Exceptions;

namespace WpfClient.Application.ViewModels
{
    /// <summary>
    /// 用户管理ViewModel，展示CommunityToolkit.Mvvm的高级功能
    /// </summary>
    public partial class UserManagementViewModel : BaseViewModel
    {
        private readonly IUserService _userService;
        private readonly ILogger<UserManagementViewModel> _logger;

        [ObservableProperty]
        private ObservableCollection<User> _users = new();

        [ObservableProperty]
        private User? _selectedUser;

        [ObservableProperty]
        private string _newUserName = string.Empty;

        [ObservableProperty]
        private string _newUserEmail = string.Empty;

        [ObservableProperty]
        private bool _isLoading;

        [ObservableProperty]
        private string _statusMessage = "就绪";

        [ObservableProperty]
        private bool _hasSelectedUser;

        public UserManagementViewModel(IUserService userService, ILogger<UserManagementViewModel> logger)
        {
            _userService = userService;
            _logger = logger;
            
            _logger.LogInformation("UserManagementViewModel 已初始化");
        }

        [RelayCommand]
        private async Task LoadUsersAsync()
        {
            try
            {
                _logger.LogInformation("开始加载用户列表");
                IsLoading = true;
                StatusMessage = "正在加载用户...";

                var users = await _userService.GetAllUsersAsync();
                Users.Clear();
                foreach (var user in users)
                {
                    Users.Add(user);
                }

                StatusMessage = $"已加载 {Users.Count} 个用户";
                _logger.LogInformation("用户列表加载完成，共 {UserCount} 个用户", Users.Count);
            }
            catch (Exception ex)
            {
                var errorMessage = $"加载用户失败: {ex.Message}";
                StatusMessage = errorMessage;
                _logger.LogError(ex, "加载用户列表时发生错误");
            }
            finally
            {
                IsLoading = false;
            }
        }

        [RelayCommand(CanExecute = nameof(CanCreateUser))]
        private async Task CreateUserAsync()
        {
            try
            {
                _logger.LogInformation("开始创建用户: Name={UserName}, Email={UserEmail}", NewUserName, NewUserEmail);
                IsLoading = true;
                StatusMessage = "正在创建用户...";

                var user = await _userService.CreateUserAsync(NewUserName, NewUserEmail);
                Users.Add(user);

                // 清空输入框
                var userName = NewUserName;
                NewUserName = string.Empty;
                NewUserEmail = string.Empty;

                StatusMessage = $"用户 {user.Name} 创建成功";
                _logger.LogInformation("用户创建成功: Id={UserId}, Name={UserName}", user.Id, user.Name);
            }
            catch (BusinessException ex)
            {
                var errorMessage = $"创建用户失败: {ex.Message}";
                StatusMessage = errorMessage;
                _logger.LogWarning(ex, "创建用户失败 - 业务异常: Name={UserName}, Email={UserEmail}", NewUserName, NewUserEmail);
            }
            catch (Exception ex)
            {
                var errorMessage = $"创建用户时发生错误: {ex.Message}";
                StatusMessage = errorMessage;
                _logger.LogError(ex, "创建用户时发生系统错误: Name={UserName}, Email={UserEmail}", NewUserName, NewUserEmail);
            }
            finally
            {
                IsLoading = false;
            }
        }

        [RelayCommand(CanExecute = nameof(CanDeleteUser))]
        private async Task DeleteUserAsync()
        {
            if (SelectedUser == null) return;

            try
            {
                _logger.LogInformation("开始删除用户: Id={UserId}, Name={UserName}", SelectedUser.Id, SelectedUser.Name);
                IsLoading = true;
                StatusMessage = $"正在删除用户 {SelectedUser.Name}...";

                var userToDelete = SelectedUser;
                await _userService.DeleteUserAsync(SelectedUser.Id);
                Users.Remove(SelectedUser);
                SelectedUser = null;

                StatusMessage = "用户删除成功";
                _logger.LogInformation("用户删除成功: Id={UserId}, Name={UserName}", userToDelete.Id, userToDelete.Name);
            }
            catch (BusinessException ex)
            {
                var errorMessage = $"删除用户失败: {ex.Message}";
                StatusMessage = errorMessage;
                _logger.LogWarning(ex, "删除用户失败 - 业务异常: Id={UserId}", SelectedUser?.Id);
            }
            catch (Exception ex)
            {
                var errorMessage = $"删除用户时发生错误: {ex.Message}";
                StatusMessage = errorMessage;
                _logger.LogError(ex, "删除用户时发生系统错误: Id={UserId}", SelectedUser?.Id);
            }
            finally
            {
                IsLoading = false;
            }
        }

        [RelayCommand]
        private void ClearForm()
        {
            _logger.LogDebug("清空用户管理表单");
            NewUserName = string.Empty;
            NewUserEmail = string.Empty;
            SelectedUser = null;
            StatusMessage = "表单已清空";
        }

        // CanExecute 方法
        private bool CanCreateUser()
        {
            return !IsLoading && 
                   !string.IsNullOrWhiteSpace(NewUserName) && 
                   !string.IsNullOrWhiteSpace(NewUserEmail);
        }

        private bool CanDeleteUser()
        {
            return !IsLoading && SelectedUser != null;
        }

        // 属性变化时的处理
        partial void OnSelectedUserChanged(User? value)
        {
            HasSelectedUser = value != null;
            
            // 通知命令状态可能已更改
            DeleteUserCommand.NotifyCanExecuteChanged();
        }

        partial void OnNewUserNameChanged(string value)
        {
            // 当用户名改变时，通知创建命令的状态可能已更改
            CreateUserCommand.NotifyCanExecuteChanged();
        }

        partial void OnNewUserEmailChanged(string value)
        {
            // 当邮箱改变时，通知创建命令的状态可能已更改
            CreateUserCommand.NotifyCanExecuteChanged();
        }

        partial void OnIsLoadingChanged(bool value)
        {
            // 当加载状态改变时，通知所有命令的状态可能已更改
            CreateUserCommand.NotifyCanExecuteChanged();
            DeleteUserCommand.NotifyCanExecuteChanged();
        }
    }
}